import * as React from 'react';
import type { Section } from './types';

const { useReducer, useEffect } = React;
interface CityDataType {
  cityData?: {
    cityList: Section[];
    hotCities: { name: string }[];
  };
  isLoading: boolean;
  error: boolean;
}
const cityDataObj: CityDataType = {
  cityData: {
    cityList: [],
    hotCities: [],
  },
  isLoading: false,
  error: false,
};
interface CityAction {
  type: string;
  payload?: {
    cityList: Section[];
    hotCities: { name: string }[];
  };
}
function cityDataReducer(
  state: CityDataType,
  action: CityAction
): CityDataType {
  const { type, payload } = action;
  switch (type) {
    case 'success':
      return {
        ...state,
        cityData: {
          cityList: payload ? payload.cityList : [],
          hotCities: payload ? payload?.hotCities : [],
        },
        isLoading: false,
        error: false,
      };
    case 'loading':
      return {
        ...state,
        isLoading: true,
      };
    case 'error':
      return {
        ...state,
        cityData: {
          cityList: [],
          hotCities: [],
        },
        isLoading: false,
        error: true,
      };
    default:
      return state;
  }
}
export default function useCity(show: boolean) {
  const [{ cityData, isLoading, error }, dispatch] = useReducer(
    cityDataReducer,
    cityDataObj
  );
  const fetchCityData = () => {
    // const cache = JSON.parse(localStorage.getItem('city_data_cache') || '{}');
    // if (Date.now() < cache.expires) {
    //   dispatch({ type: 'success', payload: cityData });
    //   return;
    // }
    dispatch({ type: 'loading' });
    fetch('/api/rest/cities?_' + Date.now())
      .then((res) => res.json())
      .then((res) => {
        dispatch({
          type: 'success',
          payload: {
            cityList: res.data.cityList,
            hotCities: res.data.hotCities,
          },
        });
        localStorage.setItem(
          'city_data_cache',
          JSON.stringify({
            expires: Date.now() + 60 * 1000,
            data: cityData,
          })
        );
      })
      .catch(() => {
        dispatch({ type: 'error' });
      });
  };
  useEffect(() => {
    if (
      !show ||
      isLoading ||
      (cityData?.cityList && cityData?.cityList.length > 0)
    ) {
      return;
    }
    fetchCityData();
  }, [show, cityData, isLoading]);
  return {
    cityData,
    isLoading,
    error,
  };
}
